package com.superbytecode.stencil.controller;

import com.superbytecode.stencil.entities.code.CodeContext;
import com.superbytecode.stencil.entities.GeneratorReq;
import com.superbytecode.stencil.entities.WebResult;
import com.superbytecode.stencil.service.CodeGeneratorService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * All rights Reserved, Designed By www.super-master.com
 *
 * @ProjectName: code-stencil
 * @Package: com.superbytecode.stencil.controller
 * @ClassName: CodeGeneratorController
 * @Description: []
 * <p> </p>
 * @Author: [Lance Ting]
 * @Date: 2024/10/11 18:03
 * @Version: V1.0
 * @Copyright: 2024 www.super-master.cn Inc. All rights reserved.
 * TODO: 注意,本文件Lance Ting所作,如果转载或使用请标明具体出处!
 **/
@Slf4j
@RestController
@RequestMapping("generate")
public class CodeGeneratorController {
    @Resource
    private CodeGeneratorService codeGeneratorService;

    /**
     * 标准模板生编码
     *
     * @param generatorReq 参数
     * @return 列表
     */
    @RequestMapping("/codeForStandard")
    public WebResult<?> createCodeForStandard(@RequestBody GeneratorReq generatorReq, HttpServletResponse response) {
        CodeContext context = null;
        try {
            context = codeGeneratorService.createCodeForStandard(generatorReq);
            byte[] codeContexts = context.getContent();
            response.reset();
            response.setHeader("Content-Disposition", "attachment; filename=\"" + context.getFileName() + "\"");
            response.addHeader("Content-Length", "" + codeContexts.length);
            response.setContentType("application/octet-stream; charset=UTF-8");
            IOUtils.write(codeContexts, response.getOutputStream());
        } catch (Exception e) {
            log.error("create code template error ", e);
            return WebResult.failure(e.getMessage());
        }
        return WebResult.success(context);
    }


    /**
     * 自定义模板生编码
     *
     * @param generatorReq 参数
     * @return 列表
     */
    @RequestMapping("/codeForCustomized")
    public WebResult<?> createCodeForCustomized(@RequestBody GeneratorReq generatorReq) {
        WebResult<?> webResult;
        try {
            List<CodeContext> codeContexts = codeGeneratorService.createCodeForCustomized(generatorReq);
            webResult = WebResult.success(codeContexts);
        } catch (Exception e) {
            log.error("create code template error ", e);
            webResult = WebResult.failure(e.getMessage());
        }
        return webResult;
    }
}